const Router = require('koa-router');
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
router.post('/app/getCustomerList', async ctx => {
    let tenantId= ctx.user.tenantId
    let uid= ctx.user.id
    let body= ctx.request.body
    let currentPage= body.currentPage
    let keyWord= body.keyWord?body.keyWord:''
    let pageSize= body.pageSize?body.pageSize:30
    let offset = (currentPage - 1) * pageSize;

    let sql = `select id,name,address,linkName,linkMobile from contact where tenantId=${tenantId} `
    if(keyWord) {
        sql += ` and(name like '%${keyWord}%' or pinYin like '%${keyWord}%' or address like '%${keyWord}%' or linkMobile like '%${keyWord}%'  or linkName like '%${keyWord}%' ) `
    }
    let total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
    let list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
    return ctx.suc('', {
        total: total.total,
        list
    })

   if(keyWord) {
       let sql = `select id,name,address,linkName,linkMobile from contact where tenantId=${tenantId} `
       if(keyWord) {
           sql += ` and(name like '%${keyWord}%' or pinYin like '%${keyWord}%' or address like '%${keyWord}%' or linkMobile like '%${keyWord}%'  or linkName like '%${keyWord}%' ) `
       }
       let total = await db.query(`select count(*) total from (${sql}) a `,{type: QueryTypes.SELECT, plain: true})
       let list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
       return ctx.suc('', {
           total: total.total,
           list
       })
   }
   else {
       let sql = `select a.id,a.name,a.address,a.linkName,a.linkMobile from contact a inner join 
      (select distinct buId,salesId from  contact_sales where tenantId=${tenantId} and salesId=${uid} ) b on a.tenantId=${tenantId} and a.id=b.buId `
       let list = await db.query(`select * from (${sql}) a order by id desc offset ${offset} rows fetch  next ${pageSize} rows only ;`,{type: QueryTypes})
       return ctx.suc('', {
           total: list.length,
           list
       })
   }
})


module.exports = router;